import traceback
from turtle import end_fill
from flask import Blueprint,render_template,jsonify,request,abort,send_from_directory
from requests.api import get
from sqlalchemy import func, and_
from sqlalchemy.log import echo_property
from sqlalchemy.orm import mapper
from sqlalchemy.sql.operators import exists
import  models
from urllib.parse import quote
import json
from werkzeug.serving import WSGIRequestHandler
WSGIRequestHandler.protocol_version = "HTTP/1.1"
from werkzeug.utils import secure_filename
import os
import config
from config import debug, log as log
from config import makeNewSession as makeNewSession
import re
import time
from uuid import uuid4
from botclass.message import Sender
from API.messageAPI import sendMaster,send_message_to
from datetime import datetime,timedelta
from random import randint
# from routes.timer import sendMsg
from botclass.timer import Timer

botLogic = Blueprint('botLogic',__name__)

@botLogic.route("/qqbot",methods=['POST'])
def qqbot():
    
    
    # print(request.get_json())
    recv = request.get_json() 

    if recv['post_type'] == 'message':
            # log(recv)
        sender = Sender(recv)
        message = recv['raw_message']
        if recv['message_type'] == 'group':   # 群聊消息
            pass
        elif recv['message_type'] == 'private': # 私聊消息
            log(f"private message {sender.nickname}-{sender.id} >> {message}")
            # await send_message(sender, message)
            print("hello")
            sendMaster(message)
            pass
    
    elif recv["post_type"] == "notice":
        if recv["notice_type"] == "group_upload":  # 有人上传群文件
            return
        elif recv["notice_type"] == "group_decrease":  # 群成员减少
            return
        elif recv["notice_type"] == "group_increase":  # 群成员增加
            return
        else:
            return
    elif recv["post_type"] == "request":
        if recv["request_type"] == "friend":  # 添加好友请求
            log(f'收到{recv["user_id"]}的好友请求')
            r = re.search(r"题1:.*?\n回答:(?P<remark>.*?)\n问题2:.*?\n回答:(?P<check>.*)", recv['comment'])
            print(r.groups('remark'),r.groups('check'))
            if int(r.groups('check')) == int(time.strftime("%m")) * int(time.strftime("%d")):
                # handleAddFriend(recv['flag'],True,r.groups('remark') or None)
                # await sendMaster(f'已同意{recv["user_id"]}的好友请求')
                pass
            else:
                # handleAddFriend(recv['flag'],False,r.groups('remark') or None)
                # await sendMaster(f'已拒绝{recv["user_id"]}的好友请求')
                pass
            pass
        if recv["request_type"] == "group":  # 加群请求
            config.debug('加群请求',recv)
            sendMaster(f'用户{recv["user_id"]}邀请我加入群聊{recv["group_id"]}')
            # config.group_invite.append({'group_id':recv['group_id'],'flag':recv["flag"],'sub_type':recv["sub_type"]})

    elif recv['post_type'] == 'meta_event':
        if recv['meta_event_type'] == 'heartbeat':
            # await timerlist.check()
            # log('heartbeat')
            pass

    else:  
        return


    return "ok"


@botLogic.route("/qqbot/sendMsgMulti",methods=['POST'])
def sendMsgMulti():
    getData = request.get_json()
    debug(getData)
    if not getData: return "some args is needed",406
    title = getData["title"]
    use_timer = getData["use_timer"]
    privates_sid = getData["send_to_who"]
    classes = getData["send_to_classes"]
    files = getData["files"]
    msg = getData["text_content"]
    session = makeNewSession()
    try:
        groups = session.query(models.Classes.mainGroup).filter(models.Classes.classesID.in_(classes)).all()
        groups = list(map(lambda d:d[0], groups))
        privates = session.query(models.Student.QQ).filter(models.Student.uid.in_(privates_sid)).all()
        privates = list(map(lambda d:d[0], privates))

        task_list = []
        if privates:
            f_msg = ''
            if files:
                for file in files:
                    q_file = session.query(models.File).filter(models.File.fileID==file).first()
                    f_msg += f"文件 {q_file.userFileName}\n{config.OUT_ADDRESS}/filedownload?id={file}\n"

            task = dict(
                type="message",
                message_type="private",
                message_list=privates,
                message=msg,
                f_msg=f_msg
            )
            task_list.append(task)
        if groups:
            task = dict(
                type="message",
                message_type="groups",
                message_list=groups,
                message=msg,
                files=files
            )
            task_list.append(task)

        if not use_timer:       # 不使用定时器            
            for task in task_list:
                if task["type"] == "message":
                    Timer.sendMsg(task, {}, session)
            
        else:           # 使用定时器
            Timer.genTimer(title, getData["week"], getData["time_day"], getData["time"], task_list, session)
        session.commit()
    except:
        traceback.print_exc()
        session.rollback()
    
    session.close()
    return "ok"




